package loveqq.jdbc.log.config;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AgentConfig {
    /**
     * 单例
     */
    public static final AgentConfig INSTANCE = new AgentConfig();

    /**
     * 开启debug模式，agent的日志也会输出
     */
    private boolean debug;
    /**
     * 排除SQL不打印(正则表达式)
     */
    private String exclude;
    /**
     * exclude编译的正则表达式
     */
    private Pattern excludePattern;


    private AgentConfig() {
    }

    /**
     * 通过配置参数初始化配置
     */
    public void load(String agentArgs) throws IllegalAccessException {
        if (agentArgs == null || agentArgs.isEmpty()) {
            return;
        }
        // 用map暂时存储配置，后面设置到字段
        Map<String, String> configMap = new HashMap<>();
        if (agentArgs.startsWith("?")) {
            // 如果开头是?就是url形式：?k1=v1&k2=v2&k3=v3
            Matcher matcher = Pattern.compile("(?<name>\\w+)=(?<value>[^&]+)").matcher(agentArgs);
            while (matcher.find()) {
                // 匹配就设置到字段
                configMap.put(matcher.group("name"), matcher.group("value"));
            }
        } else {
            // 否则通过文件来配置
            // Path path = Paths.get(agentArgs);

        }
        // 设置字段
        this.setFields(configMap);
        // 装载excludePattern
        if (this.exclude != null && !this.exclude.isEmpty()) {
            this.excludePattern = Pattern.compile(this.exclude);
        }
    }

    /**
     * 根据字段名,字段值 设置字段
     */
    private void setFields(Map<String, String> fieldMap) {
        fieldMap.forEach((name, value) -> {
            switch (name) {
                case "debug":
                    this.debug = Boolean.parseBoolean(value);
                    break;
                case "exclude":
                    this.exclude = value;
                    break;
            }
        });
    }

    public boolean isDebug() {
        return debug;
    }

    public String getExclude() {
        return exclude;
    }

    public Pattern getExcludePattern() {
        return excludePattern;
    }

    public boolean isExclude(String sql) {
        return excludePattern != null && excludePattern.matcher(sql).matches();
    }

    @Override
    public String toString() {
        return "AgentConfig{" +
                "debug=" + debug +
                ", exclude='" + exclude + '\'' +
                '}';
    }
}
